<?php
	class CommentsController extends AppController {

	var $name = 'Comments';
	var $uses = array('Comment','User','Team');
	var $paginate = array(
	'order' => array('Comment.modified' => 'asc'),
	'limit' => 5
	);
	
	function beforeFilter() {
		parent::beforeFilter();
		//$this->Auth->deny('index','add','delete');
    }	
	
	function index(){
		$comments = $this->paginate('Comment');
		
		$this->set('comments', $comments );
	}
	
	function get($url=null){
		$current_user=$this->Auth->user();
		if(!$url){
			return array();			
		}
		else{
			$this->paginate['conditions'][]['Comment.url'] = $url;
			$this->paginate['conditions'][]['Comment.status'] = 1;
			$comments=$this->paginate();
		
			foreach($comments as &$comment){
			
				$user = $this->User->findById($comment['Comment']['user_id']);
				if($current_user&&($current_user['User']['id']==$comment['Comment']['user_id']||$current_user['User']['role']==ADMIN)){
					$comment['Comment']['show']=true;
				}
				else{
					$comment['Comment']['show']=false;
				}	

				$comment['Comment']['author']=$user['User']['name'];				
				$comment['Comment']['avatar']=$user['User']['avatar'];
			}
			return $comments;
		}
	}
		
	function add($url_encode=null) {
		//decode:
		$user=$this->Auth->user();
		if($user){
			$url=str_replace('!','/',$url_encode);
			//debug($url);
				if(!empty($this->data)){
					$this->data['Comment']['url']=$url;
					$this->data['Comment']['user_id']=$user['User']['id'];
					if($this->Comment->save($this->data)){
						$this->Session->setFlash(__('Add Comment successfully!',true));
						$this->redirect($url);
					}
					else{
						$this->Session->setFlash('Error saving Comment.',true);
						$this->redirect($url);
					}
				}
		}
	}
	
	
	function delete($id) {
		$comment=$this->Comment->findById($id);
		$url=$comment['Comment']['url'];
		$current_user=$this->Auth->user();
		if($current_user&&($current_user['User']['id']==$comment['Comment']['user_id']||$current_user['User']['role']==ADMIN)){
		}
		else{
			$this->Session->setFlash('<div class="content"><div class="success">The comment with id: '.$id.' fail to be deleted.</div></div>');
			$this->redirect($url);
		}
		if($this->Comment->delete($id)){
	
			$this->Session->setFlash('The comment has been deleted.');
			$this->redirect($url);
			
		}
		else{
			$this->Session->setFlash('<div class="content"><div class="error">The comment with id: '.$id.' fail to be deleted.</div></div>');
			$this->redirect($url);
		}
	}
	
}
?>
